﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace UIWPF
{
    public static class RichTextBoxUtility
    {
        public static void RtbAppendStr(RichTextBox rtb, string str)
        {
            rtb.AppendText(str);
            rtb.FontFamily = new FontFamily("Arial");
            rtb.Document.LineHeight = 1;
            rtb.Focus();
            rtb.ScrollToEnd();
        }

        public static string GetRichTextBoxContent(RichTextBox rtb)
        {
            string res =
                new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text;
//            res = res.Substring(0, res.Length - 2);
            res = res.Replace("\r", "");
            SetRichTextBoxContent(rtb, res);
            string res2 =
                new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text;
            return res;
        }

        public static void SetRichTextBoxContent(RichTextBox rtb, string content)
        {
            rtb.Document = new FlowDocument(new Paragraph(new Run(content)));
            FlowDocument doc = new FlowDocument();
            Paragraph p = new Paragraph();
            Run r = new Run(content);
            p.Inlines.Add(r);
            doc.Blocks.Add(p);
            rtb.Document = doc;
        }

        private static TextPointer GetPoint(TextPointer start, int x)
        {
            TextPointer ret = start;
            int i = 0;
            while (i < x && ret != null)
            {
                if (ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text ||
                    ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.None)
                {
                    i++;
                }
                if (ret.GetPositionAtOffset(1, LogicalDirection.Forward) == null)
                {
                    return ret;
                }
                ret = ret.GetPositionAtOffset(1, LogicalDirection.Forward);
            }
            return ret;
        }

        public static void Colorize(RichTextBox rtb, int startPosX, int len, Color c)
        {
            TextPointer start = rtb.Document.ContentStart;
            TextPointer startPos = GetPoint(start, startPosX);
            TextPointer endPos = GetPoint(start, startPosX + len);

            TextRange range = rtb.Selection;
            range.Select(startPos, endPos);
            range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(c));
            range.Select(rtb.Document.ContentEnd, rtb.Document.ContentEnd);
        }
    }
}
